import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:yp/Xwidgets/dialog.dart';
import 'package:yp/city_information.dart';
import 'package:yp/helper.dart';
import 'package:yp/services/api.dart';
import 'package:get/get.dart' hide MultipartFile hide FormData;
import 'package:dio/dio.dart';
import 'package:sp_util/sp_util.dart';

import 'state.dart';

class MemberInformationLogic extends GetxController {
  final state = MemberInformationState();

  @override
  void onInit() {
    super.onInit();
    Map userMap = Get.arguments ?? {};

    state.nickName = userMap['nick_name'] ?? '';
    state.accountNumberController = TextEditingController(text: userMap['mobile'] ?? '');
    state.nameController = TextEditingController(text: userMap['usr_name'] ?? '');
    state.birthdayController = TextEditingController(text: userMap['birthday'] ?? '');

    state.occupationController = TextEditingController(text: userMap['iddustry'] ?? '');
    state.emailController = TextEditingController(text: userMap['r_email'] ?? '');
    String city = '${userMap['prv_name'] ?? ''} ${userMap['city_name'] ?? ''} ${userMap['city_area_name'] ?? ''}';
    if (city.replaceAll(' ', '') == '') {
      city = '';
    }
    state.cityController = TextEditingController(text: city);
    state.provinceStr = userMap['prv_num_id']?.toString() ?? '';
    state.cityStr = userMap['city_num_id']?.toString() ?? '';
    state.areaStr = userMap['city_area_num_id']?.toString() ?? '';
    state.addressController = TextEditingController(text: userMap['adr'] ?? '');
    state.headPortraitStr = userMap['logo'] ?? '';
    state.genderIndex = userMap['sex_id'] ?? 0;
    state.areasInterestStr = userMap['fvae_product'] ?? '';
    state.areasInterestList = [
      {
        'nameStr': '燃气服务',
        'chooseBool': false,
      },
      {
        'nameStr': '扶贫助农',
        'chooseBool': false,
      },
      {
        'nameStr': '直播',
        'chooseBool': false,
      },
      {
        'nameStr': '美食',
        'chooseBool': false,
      },
      {
        'nameStr': '柴米油盐',
        'chooseBool': false,
      },
      {
        'nameStr': '护肤',
        'chooseBool': false,
      },
      {
        'nameStr': '时尚穿搭',
        'chooseBool': false,
      },
      {
        'nameStr': '健康养生',
        'chooseBool': false,
      },
      {
        'nameStr': '宠物养护',
        'chooseBool': false,
      },
      {
        'nameStr': '智能产品',
        'chooseBool': false,
      },
      {
        'nameStr': '医疗保健',
        'chooseBool': false,
      },
      {
        'nameStr': '家居家装',
        'chooseBool': false,
      },
      {
        'nameStr': '文化教育',
        'chooseBool': false,
      },
      {
        'nameStr': '学习用品',
        'chooseBool': false,
      },
      {
        'nameStr': '职场',
        'chooseBool': false,
      },
      {
        'nameStr': '办公用品',
        'chooseBool': false,
      },
      {
        'nameStr': '地方特产',
        'chooseBool': false,
      },
    ];

    var params = {
      "sql_id": "USR_USER_INFO_CHANGE_BIRTHDAY_LOG",
      "input_param": {
        "usr_num_id": SpUtil.getInt('empeNumId'),
      }
    };
    Api.classification(params).listen((event) {
      print('判断 生日 修改  event = $event');
      if (event['code'] == 0) {
        state.birthdayBool = event['results'][0]['modify_tag'].toString() == 'true';
      }
      update();
    });

    var cityParams = {
      "access_token": SpUtil.getString('token'),
    };
    Api.cityInformation(cityParams).listen((event) {
      // print('城市信息  event = $event');
      if (event['code'] == 0) {
        AddressInformation addressInformation = AddressInformation.fromJson(event);
        Map<String, dynamic> mapData = addressInformation.toJson();
        state.addressList = mapData['children'];
      }
      update();
    });
  }

  void onAreasInterestClick({String areasInterestStr}) {
    state.areasInterestStr = areasInterestStr;
    update();
  }

  void modifyInformation(BuildContext context) {
    if (state.nameController.text == '') {
      toast('请输入姓名');
      return;
    }
    if (state.birthdayController.text == '') {
      toast('请输选择生日');
      return;
    }
     if (state.cityController.text == '') {
      toast('请选择城市');
      return;
    }
     if (state.addressController.text == '') {
       toast('请填写详细地址');
       return;
     }

     EasyLoading.show();
    if (state.imageData != null) {
      MultipartFile multipartFile = MultipartFile.fromBytes(
        state.imageData,
        filename: 'a.jpg',
      );
      Api.upImage(
        FormData.fromMap({
          "file": multipartFile,
        }),
      ).listen((event) {
        print(' 上传成功  event = $event');
        if (event["code"] == 0) {
          String urlStr = event['result'][0]['url'];
          var params = {
            "user_name": state.nameController.text,
            "nick_name": state.nickName,
            "birthday": state.birthdayController.text,
            "sex_id": state.genderIndex,
            "iddustry": state.occupationController.text,
            "r_email": state.emailController.text,
            "fvae_product": state.areasInterestStr,
            "adr": state.addressController.text,
            "prv_num_id": state.provinceStr,
            "city_num_id": state.cityStr,
            "city_area_num_id": state.areaStr,
            "logo": urlStr,
            "access_token": SpUtil.getString('token'),
          };
          Api.modifyInformation(params).listen((event) {
            EasyLoading.dismiss();
            print(' 修改会员信息 返回数据  $event');
            if (event['code'] == 0) {
              var data = {
                'usr_num_id': SpUtil.getInt('empeNumId'),
              };
              Api.awardinfoget(data).listen((event) {
                print(' 修改会员信息 返回数据  $event');
                if (event['code'] == 0) {
                          if(event['award_sign '] == 0 && event['activity_sign '] == 1){
                      YpShowDialog.showCompleteMemberReward(context,event);
                  }
                  // Get.back();
                }
              });
              toast('保存成功');
              // Get.back();
            } else {
              toast('保存失败');
            }
          }, onDone: () {
            EasyLoading.dismiss();
          });
        } else {
          EasyLoading.dismiss();
        }
      }, onDone: () {
        EasyLoading.dismiss();
      });
    } else {
      var params = {
        "user_name": state.nameController.text,
        "nick_name": state.nickName,
        "birthday": state.birthdayController.text,
        "sex_id": state.genderIndex,
        "iddustry": state.occupationController.text,
        "r_email": state.emailController.text,
        "fvae_product": state.areasInterestStr,
        "adr": state.addressController.text,
        "prv_num_id": state.provinceStr,
        "city_num_id": state.cityStr,
        "city_area_num_id": state.areaStr,
        "logo": state.headPortraitStr,
        "access_token": SpUtil.getString('token'),
      };
      Api.modifyInformation(params).listen((event) {
        EasyLoading.dismiss();
        print(' 修改会员信息 返回数据  $event');
        if (event['code'] == 0) {
          toast('保存成功');
          Get.back();
        } else {
          toast('保存失败');
        }
      }, onDone: () {
        EasyLoading.dismiss();
      });
    }
  }
}
